package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 11258
* @description 针对表【category(菜品及套餐分类)】的数据库操作Service实现
* @createDate 2024-03-21 16:27:12
*/
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private DishMapper dishMapper;
    @Resource
    private SetmealMapper setmealMapper;

    @Override
    public R<String> add(Category category) {
        log.info(category.toString());
        categoryMapper.insert(category);
        return R.success("新增分类成功!");
    }


    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishQueryWrapper=new LambdaQueryWrapper<Dish>();
        //添加查询条件
        dishQueryWrapper.eq(Dish::getCategoryId,id);
        int count = dishMapper.selectCount(dishQueryWrapper);
        //查询当前分类下是否关联了菜品,
        if(count>0){
            //如果已经关联,抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品,不能删除");
        }
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper=new LambdaQueryWrapper<Setmeal>();
        setmealQueryWrapper.eq(Setmeal::getCategoryId,id);
        count = setmealMapper.selectCount(setmealQueryWrapper);
        //查询当前分类下是否关联了套餐,
        if(count>0){
            //如果已经关联,抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐,不能删除");
        }
        //正常删除分类
        super.removeById(id);
    }

    @Override
    public R<String> setById(Category category) {
        log.info(category.toString());
        categoryMapper.updateById(category);
        return R.success("修改分类信息成功!");
    }

    @Override
    public R<List<Category>> all(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> query = new LambdaQueryWrapper<>();
        query.eq(category.getType() != null,Category::getType,category.getType());
        //添加排序
        query.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> lists = categoryMapper.selectList(query);
        return R.success(lists);
    }
}




